package com.boolib.shopadmin.config.shiro.realm;


import com.boolib.commons.Const;
import com.boolib.commons.entity.ServerResponse;
import com.boolib.pojo.SysUser;
import com.boolib.service.IAdminService;


import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.io.Serializable;


@Slf4j
public class MyRealm extends AuthorizingRealm implements Serializable {




    @Autowired
    IAdminService adminService;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        Subject subject = SecurityUtils.getSubject();

//        SysUser user = ShiroUtils.getUser();
//
//        log.info(user.getUsername()+"获取权限");
//
//        Set<String> roles = userService.getRoleById(user.getUid());
//
//
//        Set<String> permissions = new HashSet<>();
//
//        List<SysMenu> syses = userService.getPermissionById(user.getUid());
//
//
//        for (SysMenu sy :syses) {
//
//            permissions.add(sy.getPerms());
//
//        }
//
//
//
//
//
//
//        simpleAuthorizationInfo.addRoles(roles);
//
//        simpleAuthorizationInfo.addStringPermissions(permissions);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo ;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        String username = usernamePasswordToken.getUsername();


        String password = new String(usernamePasswordToken.getPassword());



        SysUser temp =  new SysUser();

        temp.setUsername(username);

        temp.setPassword(password);



        ServerResponse serverResponse =adminService.sysUserLoginAuth(temp);

        if(!serverResponse.isSuccess() ){

            log.info("code:"+serverResponse.getStatus()+","+serverResponse.getMsg());

            throw new AuthenticationException(serverResponse.getMsg());
         }



         Session session =  SecurityUtils.getSubject().getSession();

         session.setAttribute(Const.SysUser.SESSIONAUTH,serverResponse.getData());

        return  new SimpleAuthenticationInfo(serverResponse.getData(),authenticationToken.getCredentials(),getName());
    }



    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo()
    {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
